package com.ma.imserver.netty.ws;

import com.ma.imserver.netty.IMChannelHandler;
import com.ma.imserver.netty.IMServer;
import com.ma.imserver.netty.ws.endecode.MessageProtocolDecoder;
import com.ma.imserver.netty.ws.endecode.MessageProtocolEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.EventListener;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "websocket",value = "enable",havingValue = "true",
matchIfMissing = false)
public class WebSocketServer implements IMServer {
    @Value("${websocket.port}")
    private int port;

    private volatile boolean ready = false;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @Override
    public boolean isReady() {
        return ready;
    }

    @Override
    public void stop() {
        if (bossGroup != null && !bossGroup.isShutdown() && !bossGroup.isShuttingDown()) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null && !workerGroup.isShutdown() && !workerGroup.isShuttingDown()) {
            workerGroup.shutdownGracefully();
        }
        this.ready = false;
        log.info("TcpSocketServer stopped");
    }

    @Override
    public void start() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        //设置为主从线程模型
        bootstrap.group(bossGroup, workerGroup)
                //设置为服务端NIO通信类型
                .channel(NioServerSocketChannel.class)
                //设置ChannelPipleLine
                .childHandler(new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        // 获取职责链
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                        pipeline.addLast("http-codec", new HttpServerCodec());
                        pipeline.addLast("aggregator", new HttpObjectAggregator(65535));
                        pipeline.addLast("http-chunked", new ChunkedWriteHandler());
                        pipeline.addLast(new WebSocketServerProtocolHandler("/im"));
                        pipeline.addLast("encode", new MessageProtocolEncoder());
                        pipeline.addLast("decode", new MessageProtocolDecoder());
                        pipeline.addLast("handler", new IMChannelHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 5)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
    }
}
